package cn.itsource.service.impl;

import cn.itsource.config.rabbitmq.RabbitmqConfig;
import cn.itsource.doc.CourseDoc;
import cn.itsource.domain.Course;
import cn.itsource.domain.CourseDetail;
import cn.itsource.domain.CourseMarket;
import cn.itsource.dto.CourseAddDto;
import cn.itsource.dto.SmsDto;
import cn.itsource.exception.MyException;
import cn.itsource.feign.client.CourseFeignClient;
import cn.itsource.mapper.CourseDetailMapper;
import cn.itsource.mapper.CourseMapper;
import cn.itsource.mapper.CourseMarketMapper;
import cn.itsource.query.CourseQuery;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ICourseService;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fengluochen
 * @since 2022-11-12
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private CourseDetailMapper courseDetailMapper;
    @Resource
    private CourseMarketMapper courseMarketMapper;
    @Resource
    private CourseFeignClient courseFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public Page<CourseAddDto> selectMyPage(CourseQuery query) {
        Page<CourseAddDto> page = new Page<>(query.getPage(), query.getRows());
        List<CourseAddDto> courseAddDtoList = courseMapper.selectMyPage(page, query.getKeyword());
        return page.setRecords(courseAddDtoList);
    }

    @Override
    public void saveOrUpdate(CourseAddDto dto) {
        //获取课程
        Course course = dto.getCourse();
        //设置上下线
        course.setStatus(0); //0下线 1,上线
        //TODO 待做的事情
        course.setUserId(null);
        course.setUserName(null);
        course.setTenantId(null);
        course.setTenantName(null);
        courseMapper.insert(course);
        //获取详情
        CourseDetail courseDetail = dto.getCourseDetail();
        //设置id
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);
        //获取市场
        CourseMarket courseMarket = dto.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);
    }

    @Override
    public JSONResult onLineCourse(CourseQuery query) {
//          1.入参校验
        Long[] ids = query.getIds();
        if(ids==null){
            throw new MyException("请勾选上线课程");
        }
//          2.根据id集合查询所有课程纪录
        List<Course> courses = courseMapper.selectBatchIds(Arrays.asList(ids));
//         3.修改状态
        //准备list集合
        ArrayList<CourseDoc> courseDocs = new ArrayList<>();
        CourseDoc courseDoc=null;
        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);
            if(course.getStatus()==0){
                course.setStatus(1); //0下线 1上线
                course.setOnlineTime(new Date());
                //更新状态
                courseMapper.updateById(course);
                //准备存es
                CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());
                //copy对象
                courseDoc = new CourseDoc();
                BeanUtils.copyProperties(course,courseDoc);
                BeanUtils.copyProperties(courseMarket,courseDoc);
                //以集合的方式存
                courseDocs.add(courseDoc);
            }
        }
//         4.课程数据存es
        //如果list有值就存
        if(courseDocs.size()>0){
            JSONResult result = courseFeignClient.saveBatchCourse2Es(courseDocs);
            if(!result.isSuccess()){
                throw new MyException(result.getMessage());
            }
        }else {
            throw new MyException("没有课程需要上线");
        }
//         5.发营销信息
        //需要接受短信的用户集合
        ArrayList<String> phoneList = new ArrayList<>();
        String smsContent="尊敬的xxxx用户，我们课程有上新，快来体验，前100名，只需要19.9元，链接：http://www.baidu.com";
        SmsDto smsDto = new SmsDto();
        smsDto.setContent(smsContent);
        smsDto.setPhone(phoneList);
        //发短信信息
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_HRM,
                "course.sms",smsDto,new MyMessage());
        //发送邮件消息
        rabbitTemplate.convertAndSend(
                RabbitmqConfig.EXCHANGE_HRM,
                "course.email",
                smsContent,new MyMessage());
        return JSONResult.success();
    }

    @Override
    public JSONResult offLineCourse(CourseQuery query) {
//          1.入参校验
        Long[] ids = query.getIds();
        if(ids==null){
            throw new MyException("请勾选下线课程");
        }
//          2.根据id集合查询所有课程纪录
        List<Course> courses = courseMapper.selectBatchIds(Arrays.asList(ids));
//         3.修改状态
        //准备list集合
        ArrayList<CourseDoc> courseDocs = new ArrayList<>();
        CourseDoc courseDoc=null;
        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);
            if(course.getStatus()==1){
                course.setStatus(0); //0下线 1上线
                course.setOfflineTime(new Date());
                //更新状态
                courseMapper.updateById(course);
                //准备存es
                CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());
                //copy对象
                courseDoc = new CourseDoc();
                BeanUtils.copyProperties(course,courseDoc);
                BeanUtils.copyProperties(courseMarket,courseDoc);
                //以集合的方式存
                courseDocs.add(courseDoc);
            }
        }
//         4.课程数据存es
        //如果list有值就存
        if(courseDocs.size()>0){
            JSONResult result = courseFeignClient.deleteBatchCourseFromEs(courseDocs);
            if(!result.isSuccess()){
                throw new MyException(result.getMessage());
            }
        }else {
            throw new MyException("没有课程需要下线");
        }

        return JSONResult.success();
    }
}
class MyMessage implements MessagePostProcessor {

    @Override
    public Message postProcessMessage(Message message) throws AmqpException {
        //消息持久化
        message.getMessageProperties().setReceivedDeliveryMode(MessageDeliveryMode.PERSISTENT);
        return message;
    }
}
